import axios from "axios";
import 'element-plus/es/components/message/style/css'
import {ElMessage} from 'element-plus'
import Router from '../router/index.js'


var request = axios.create({
    baseURL: serverApiHost.url,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

export function get(url, params) {
    request.defaults.headers.Authorization = localStorage.getItem('auth-system-token');
    return new Promise((resolve, reject) => {
        request.get(url, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            ElMessage({message:'服务器异常，请稍后重试',type:'error'})
            reject(err);
        })
    })
}

export function rest(url, params) {
    request.defaults.headers.Authorization = localStorage.getItem('auth-system-token');
    return new Promise((resolve, reject) => {
        request.get(url+'/'+params).then(res => {
            resolve(res.data);
        }).catch(err => {
            ElMessage({message:'服务器异常，请稍后重试',type:'error'})
            reject(err);
        })
    })
}

export function post(url, params) {
    request.defaults.headers.Authorization = localStorage.getItem('auth-system-token');
    return new Promise((resolve, reject) => {
        request.post(url, JSON.stringify(params))
            .then(res => {
                resolve(res.data);
            }).catch(err => {
                ElMessage({message:'服务器异常，请稍后重试',type:'error'})
                reject(err);
            })
    })
}

export function del(url, params) {
    request.defaults.headers.Authorization = localStorage.getItem('auth-system-token');
    return new Promise((resolve, reject) => {
        request.delete(url,{data:params}).then(res => {
            resolve(res.data);
        }).catch(err => {
            ElMessage({message:'服务器异常，请稍后重试',type:'error'})
            reject(err);
        })
    })
}

export function put(url, params) {
    request.defaults.headers.Authorization = localStorage.getItem('auth-system-token');
    return new Promise((resolve, reject) => {
        request.put(url,JSON.stringify(params)).then(res => {
            resolve(res.data);
        }).catch(err => {
            ElMessage({message:'服务器异常，请稍后重试',type:'error'})
            reject(err);
        })
    })
}


request.interceptors.response.use(
    response => {
        if(response.headers.token){
            localStorage.setItem('auth-system-token',response.headers.token)
        }
        if (response.data.code == 401) {
            // ElMessage({message:response.data.msg,type:'error'})
            Router.push('/login')
        }
        if (response.data.code == 403) {
            // ElMessage({message:response.data.msg,type:'error'})
        }
        if (response.data.code == 503) {
            ElMessage({message:'服务正维护或重启，请稍后重试',type:'error'})
        }
        return response;
    }
)